<?php


namespace app\engine\controller;


use cmf\controller\HomeBaseController;
use think\Db;

class CoorController extends HomeBaseController
{
    public function index()
    {
        $data = $this->request->param();
        $res = Db::name('coor')->where(['eid' => $data['id']])->order('date desc')->select()->toArray();
        foreach ($res as $k => &$v){
            $v['sname']= Db::name('staff')->where(['id'=>$v['sid']])->value('name');
        }
        $all = Db::name('coor')->where(['eid' => $data['id']])->sum('price');
        $lea = Db::name('coor')->where(['eid' => $data['id'], 'type' => 1])->sum('price');
        $sup = Db::name('coor')->where(['eid' => $data['id'], 'type' => 2])->sum('price');
        $this->assign('all', $all);
        $this->assign('lea', $lea);
        $this->assign('sup', $sup);
        $this->assign('res', $res);
        $this->assign('id', $data['id']);
        return $this->fetch();
    }

    public function add()
    {
        $data = $this->request->param();
        $leader = Db::name('leader')->where(['eid' => $data['id']])->field('id,name,type')->select()->toArray();
        $staff = Db::name('staff')->select()->toArray();
        if ($data['type'] == 1) {
            $type = 1;
        } elseif ($data['type'] == 2) {
            $type = 2;
        }
        $this->assign('id', $data['id']);
        $this->assign('staff', $staff);
        $this->assign('leader', $leader);
        $this->assign('type', $type);
        return $this->fetch();
    }

    public function doadd()
    {
        $data = $this->request->param();
        if (empty($data['date']) || empty($data['name']) || empty($data['price']) || empty($data['desc'])) {
            $this->error('请填写必要参数');
        }
        $files = $this->request->file('img');
        unset($data['img']);
        if ($files) {
            foreach ($files as $k => $file) {
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
                if ($info) {
                    $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
                } else {
                    $this->error($file->getError());
                }
            }
            $data['img'] = implode(',', $kps);
        }
        $res = Db::name('coor')->insert($data);
        if (!$res) {
            $img = explode(',', $data['img']);
            foreach ($img as $k => $v) {
                $v = CMF_ROOT . 'public' . $v;
                if ($v != CMF_ROOT . 'public' && file_exists($v)) {
                    unlink($v);
                }
            }
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function del()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 3 || $role == 5){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $check = Db::name('coor')->where(['id' => $data['id']])->find();
        if ($check['img']) {
            $img = explode(',', $check['img']);
            foreach ($img as $k => $v) {
                $v = CMF_ROOT . 'public' . $v;
                if ($v != CMF_ROOT . 'public' && file_exists($v)) {
                    unlink($v);
                }
            }
        }
        $res = Db::name('coor')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function see()
    {
        $data = $this->request->param();
        $res = Db::name('coor')->where(['id' => $data['id']])->find();
        $res['img'] = explode(',', $res['img']);
        foreach ($res['img'] as $k => &$v) {
            $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
        }

        $res['sname'] = Db::name('staff')->where(['id' => $res['sid']])->value('name');
        $staff = Db::name('staff')->select()->toArray();
        $this->assign('id', $res['eid']);
        $this->assign('staff', $staff);
        $this->assign('res', $res);
        return $this->fetch();
    }

    public function doedit()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 3 || $role == 5){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $files = request()->file('img');
        $id = $data['id'];
        unset($data['id']);
        $check = Db::name('coor')->where(['id' => $id])->find();

        // 处理要删除的图片
        $removeImg = isset($data['remove_img']) ? $data['remove_img'] : [];
        unset($data['remove_img']);

        // 处理保留的旧图片
        $oldImg = isset($data['old_img']) ? $data['old_img'] : [];
        unset($data['old_img']);

        // 处理凭证图片
        if (!is_null($files) || !empty($removeImg)) {
            $kps = [];
            // 如果有旧图片，先添加到数组中
            if (!empty($oldImg)) {
                // 处理旧图片，去除域名只保留路径
                foreach ($oldImg as $img) {
                    if (!empty($img)) {
                        // 如果图片路径包含域名，只保留路径部分
                        if (strpos($img, 'http://') === 0 || strpos($img, 'https://') === 0) {
                            $parsedUrl = parse_url($img);
                            $kps[] = $parsedUrl['path'];
                        } else {
                            $kps[] = $img;
                        }
                    }
                }
            } else if (!empty($check['img']) && empty($removeImg)) {
                // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $imgArray = explode(',', $check['img']);
                foreach ($imgArray as $img) {
                    if (!empty($img)) {
                        $kps[] = $img;
                    }
                }
            }

            // 处理新上传的图片
            if (!is_null($files)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['img'] = implode(',', $kps);
        }

        // 更新数据库
        $res = Db::name('coor')->where('id', $id)->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        
        // 删除被标记为删除的图片
        if (!empty($removeImg)) {
            foreach ($removeImg as $img) {
                $path = CMF_ROOT . 'public' . $img;
                if (file_exists($path)) {
                    unlink($path);
                }
            }
        }
        
        $this->success('操作成功');
    }
}